package com.zs.hydrant.mapper;

import com.zs.hydrant.entity.FireHydrant;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.*;
import java.math.BigDecimal;

@Mapper
public interface FireHydrantMapper {
    /**
     * 查询中山市内，距离用户最近的消防栓
     * @param userLat 用户纬度
     * @param userLon 用户经度
     * @return 按距离排序的消防栓列表
     */
    @Select("SELECT *, " +
            "(6371 * 2 * ASIN(SQRT(POWER(SIN((#{userLat} - latitude) * PI() / 180 / 2), 2) + " +
            "COS(#{userLat} * PI() / 180) * COS(latitude * PI() / 180) * " +
            "POWER(SIN((#{userLon} - longitude) * PI() / 180 / 2), 2)))) AS distance " +
            "FROM fire_hydrant " +
            "WHERE city = '中山市' " +
            "ORDER BY distance ASC " +
            "LIMIT 1") // 只取最近的1个
    FireHydrant findNearestHydrant(@Param("userLat") BigDecimal userLat, @Param("userLon") BigDecimal userLon);
    
    /**
     * 添加消防栓
     */
    @Insert("INSERT INTO fire_hydrant (latitude, longitude, address, city, status, photo_front, photo_side, collector_id, update_time) " +
            "VALUES (#{latitude}, #{longitude}, #{address}, #{city}, #{status}, #{photoFront}, #{photoSide}, #{collectorId}, NOW())")
    int addFireHydrant(FireHydrant fireHydrant);
    
    /**
     * 获取所有消防栓
     */
    @Select("SELECT * FROM fire_hydrant")
    List<FireHydrant> getAllFireHydrants();
    
    /**
     * 更新消防栓状态
     */
    int updateHydrantStatus(@Param("id") Integer id, @Param("status") Integer status);
    
    /**
     * 根据ID删除消防栓
     */
    @Delete("DELETE FROM fire_hydrant WHERE id = #{id}")
    void removeById(@Param("id") Integer id);
    
    /**
     * 更新消防栓信息
     */
    @Update({"UPDATE fire_hydrant SET ",
        "latitude = #{latitude}, longitude = #{longitude}, address = #{address}, ",
        "city = #{city}, status = #{status}, photo_front = #{photoFront}, ",
        "photo_side = #{photoSide}, collector_id = #{collectorId}, update_time = NOW() ",
        "WHERE id = #{id}"})
    void updateById(FireHydrant fireHydrant);

}